//
//  RDProjectsViewController.swift
//  test-ios
//
//  Created by wyz5204 on 2023/5/28.
//

import UIKit
import RxCocoa
import RxSwift
import MJRefresh
/*
 实现一个项目列表，请求数据，展示数据，
 请求数据专json，json转实体类
 */
class RDProjectsViewController: SimpleViewController<RDProjectViewModel> , UITableViewDataSource , UITableViewDelegate{
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
    }
    
    private lazy var projectTableView : UITableView = {
        let view = UITableView()
        view.dataSource = self
        view.delegate = self
        view.backgroundColor = .white
        view.register(cellType: ProjectCell.self)
        view.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
            self?.postDelay(delayTime: 3) {
                view.mj_header?.endRefreshing()
            }
        }).then({ refresh in
            refresh.setTitle("下拉刷新", for: .idle)
            refresh.setTitle("释放更新", for: .pulling)
            refresh.setTitle("正在刷新...", for: .refreshing)
            refresh.height = 50
        })
        
        view.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: { [weak self] in
            print("refresh footer >>>> ")
            self?.postDelay(delayTime: 3) {
                view.mj_footer?.endRefreshing()
            }
        }).then({ refresh in
            refresh.setTitle("上拉加载", for: .idle)
            refresh.setTitle("释放更新", for: .pulling)
            refresh.setTitle("正在刷新...", for: .refreshing)
        })
        return view
    }()
    
    
    private lazy var emptyView = {
        return EmptyDataView()
    }()
    
    override func initView(_ contentView: UIView) {
        // 添加 table
        projectTableView.addTo(contentView) { view in
            view.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
        
        self.navigationController?.navigationBar.backgroundColor = .white
    }
    
    override func bindViewModel(_ viewModel: RDProjectViewModel) {
        
        let output = viewModel.transform(RDProjectViewModel.Input.init())
        
        // 更行界面
        output.updateUIEvent.subscribe(onNext: { [weak self] _ in
            self?.projectTableView.reloadData()
        }).disposed(by: rx.disposeBag)
        
        output.finishRefreshEvent.subscribe(onNext: { [weak self] data in
            self?.projectTableView.mj_header?.endRefreshing()
        }).disposed(by: rx.disposeBag)
        
        output.finishLoadEvent.subscribe(onNext: { [weak self] data in
            self?.projectTableView.mj_footer?.endRefreshing()
        }).disposed(by: rx.disposeBag)
        
        // 判断是否存在默认的组织
        // 设置左上角的数据 判断是否存组织，如果没有则显示
        // 顶部状态栏
        let org = viewModel.getDefaultOrg()
        if(org != nil){
            print("RDProjectsViewController >>>> 1")
            navigationItem.leftBarButtonItem = UIBarButtonItem.init(
                customView: TitlePullDownButton()
            )
            
            // 说明 有组织 获取默认组织 进行数据请求 制定的 组织下的项目列表
            viewModel.getProjectList(org!.id)
        }else{
            print("RDProjectsViewController >>>> 2")
            navigationItem.leftBarButtonItem = UIBarButtonItem.init(
                customView: UILabel().then({ label in
                    label.setTitleAndColor("项目")
                })
            )
        }
        
        // 进行注册 组织的监听和变化
        // 在这进行监听即可 监听数据的变化
        registerNotificationObserver(name: RDNotification.defaultOrg) { [weak viewModel] notifice in
            if(notifice.object is OrgBean){
                let org = (notifice.object as! OrgBean)
                viewModel?.getProjectList(org.id)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let bean = self.viewModel?.projects[indexPath.row] else {
            return
        }
        // 项目选择
        navigator.show(segue: .projectDetail(projectBean: bean), sender: self)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel?.projects.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(for: indexPath , cellType: ProjectCell.self)
        cell.initBinder(tableView , self.viewModel?.projects[indexPath.row] , indexPath)
        return cell
    }
    
}


class RDProjectViewModel : SimpleViewModel , MVVMTransform{
    
    let user = RDDBModel.shared()
    let net = RDNetModel.shared
    // 进行设置数据的监听 和转换
    var projects = [ProjectBean]()
    
    let finishLoadEvent = PublishSubject<Void>()
    let finishRefreshEvent = PublishSubject<Void>()
    let updateUIEvent = PublishSubject<Void>()
    
    struct Input{
        
    }
    
    struct Output{
        let finishLoadEvent : PublishSubject<Void>
        let finishRefreshEvent : PublishSubject<Void>
        let updateUIEvent : PublishSubject<Void>
    }
    
    
    func transform(_ input: Input) -> Output {
        return Output.init( finishLoadEvent: finishLoadEvent, finishRefreshEvent: finishRefreshEvent, updateUIEvent: updateUIEvent )
    }
    
    
    func isHasDefaultOrg() -> Bool {
        return user.getDefaultOrg() != nil
    }
    
    func getDefaultOrg() -> OrgBean? {
        return user.getDefaultOrg()
    }
    
    func getProjectList(_ orgId : Int , _ page : Int = 1){
        print(" 准备进行 项目列表的请求 \(orgId)")
        net.getProjectList(orgId).subscribe(onSuccess: {[weak self] data in
            print(" getProject >>> \(data.data)")
            if(page == 1){
                self?.projects.removeAll()
                self?.projects.append(contentsOf: data.data!)
                
                // 结束刷行
                self?.finishRefreshEvent.onNext(())
            }else{
                self?.projects.append(contentsOf: data.data!)
                
                // 结束下拉加载
                self?.finishLoadEvent.onNext(())
            }
            //             进行通知 刷行界面和结束上拉下拉动作
            self?.updateUIEvent.onNext(())
            
        }).disposed(by: rx.disposeBag)
    }
    
}


